import { Apis } from "../../../service/apiimpl";
import { Entities } from "../../../service/entities"
const app = getApp()
app.BasePage({
    data: {
        ios: app.globalData.ios,
        /**
         * 线
         */
        points: [],
        hasBack:true,
        /**
         * 定位点
         */
        location: {},
        pictures: [],
        pos: { longitude: 0, latitude: 0 },
        addSpotTitle: '添加钓点',
        name: "",
        description: "",
        parkingEasy: 1,
        isFree: 1,
        secret: 1,
        lvls: 'UNRANKED',
        distance: 'TEN_MITRES',
        waterType: 'RIVER',
        spotTypes: ['KAN'],
        fishTypes: ['JIYU'],
        ctx: null,
    },
    onLoad(options) {
        const { longitude, latitude } = options
        if (longitude) {
            this.setData({ location: { longitude, latitude } })
        } else {
            Apis.getCurrentPosition((res) => {
                this.setData({
                    hasBack:false,
                    location: {
                        latitude: res.latitude,
                        longitude: res.longitude
                    }
                })
            });
        }
    },
    onShow: function () {
        Apis.loadAddSpotProperties()
            .then((props) => {
                const formatProps = (key) => this.reorganizeArray(props[key]);
                this.setData({
                    spotProps: {
                        waterTypes: formatProps('waterTypes'),
                        fishTypes: formatProps('fishTypes'),
                        spotTypes: formatProps('spotTypes'),
                        distances: formatProps('distances'),
                        lvls: formatProps('lvls')
                    }
                });
            })
            .catch(err => {
                console.error('加载钓点属性失败', err);
            });
    },
    reorganizeArray(arr: Entities.SpotProperty[], chunkSize = 4): Entities.SpotProperty[][] {
        const result: Entities.SpotProperty[][] = [];
        const tempArray = [...arr];
        if (tempArray.length > 0) {
            tempArray[0].checked = true;
        }
        while (tempArray.length > 0) {
            result.push(tempArray.splice(0, chunkSize));
        }
        return result;
    },
    async submitSpot() {
        try {
            const {
                location,
                points,
                pictures,
                name,
                description,
                lvls,
                parkingEasy,
                isFree,
                secret,
                distance,
                spotTypes,
                fishTypes,
                waterType,
                circleId
            } = this.data
            if (!name?.trim()) {
                wx.showToast({
                    title: "请填写钓点名.",
                    duration: 2000,
                    icon: "error"
                })
                return;
            }
            if (!location?.longitude) {
                wx.showToast({
                    title: "请填定位坐标.",
                    duration: 2000,
                    icon: "error"
                })
                return;
            }
            if (pictures?.length == 0) {
                wx.showToast({
                    title: "请上传图片.",
                    duration: 2000,
                    icon: "error"
                })
                return;
            }
           const result:Entities.DTO<string> = await Apis.addSpot({
                location,
                name,
                description,
                parkingEasy,
                isFree,
                secret,
                distance,
                spotTypes,
                fishTypes,
                waterType,
                circleId,
                line: points,
                lvl: lvls,
                pics: pictures,
            });
            if(result.status) {
                wx.showToast({
                    title: '添加成功',
                    icon: 'success',
                    duration: 2000
                });
                
                const pages = getCurrentPages();
                if (pages.length > 1) {
                    wx.navigateBack();
                } else {
                    wx.switchTab({ url: '/pages/spots/index'});
                }
            }
        } catch (error) {
            wx.showToast({
                title: '添加失败',
                icon: 'error',
                duration: 2000
            });
            console.error('添加钓点失败:', error);
        }
    },
    onSpotFishTypeChange(e: { detail: { value: string[] } }): void {
        if (e?.detail?.value) {
            this.setData({ fishTypes: e.detail.value })
        }
    },
    onSpotSpotTypeChange(e: { detail: { value: string[] } }): void {
        if (!e?.detail?.value?.length) return;
        this.setData({ spotTypes: e.detail.value });
    },
    onSpotWaterTypeChange(e: WechatMiniprogram.CustomEvent<{ value: string }>): void {
        try {
            this.setData({
                waterType: e.detail.value || 'RIVER'
            })
        } catch (error) {
            console.error('设置水域类型失败:', error)
        }
    },
    onSpotDistanceChange(e: WechatMiniprogram.CustomEvent<{ value: number }>) {
        this.setData({ distance: e.detail.value })
    },
    onSpotLvlsChange(e: WechatMiniprogram.CustomEvent<{ value: string }>) {
        this.setData({ lvls: e.target.dataset.prop.code })
    },
    onIsSecretChange(e: WechatMiniprogram.CustomEvent<{ value: number }>) {
        console.info("is secret:", e)
        this.setData({ secret: e.detail.value })
    },
    onIsChargeChange(e: WechatMiniprogram.CustomEvent<{ value: number }>) {
        this.setData({ isFree: e.detail.value })
    },
    onParkingChange(e: WechatMiniprogram.CustomEvent<{ value: number }>) {
        this.setData({ parkingEasy: e.detail.value })
    },
    onAddSpotClicked(event: WechatMiniprogram.CustomEvent) {
        wx.navigateTo({ url: "/pages/spots/pointpickup/index?isPos=true" })
    },
    onViewPictures(e: { target: { dataset: { pics: string[] } } }) {
        try {
            if (!e.target.dataset.pics || e.target.dataset.pics.length === 0) {
                wx.showToast({ title: '暂无图片', icon: 'none' })
                return
            }
            wx.previewImage({
                current: e.target.dataset.pics[0],
                urls: e.target.dataset.pics
            })
        } catch (error) {
            wx.showToast({ title: '预览失败', icon: 'none' })
        }
    },
    onRemovePicture(e) {
        const pictures = this.data.pictures.filter((p, i) => i != e.currentTarget.dataset.index)
        this.setData({ pictures: pictures })
    },
    onSpotNameChange(e) {
        const val = e.detail.value;
        if (val?.trim()) {
            this.setData({ hasName: true })
        }
    },
    async onAddPictures() {
        try {
            //第一次压缩
            const res = await wx.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera']
            });
            const uploadRes = await Apis.uploadFile(res.tempFilePaths[0]);
            this.setData({
                pictures: [...this.data.pictures, uploadRes.data.url]
            });

        } catch (error) {
            console.error('上传失败:', error);
            wx.showToast({
                title: `上传失败: ${error.errMsg || '未知错误'}`,
                icon: 'none',
                duration: 2000
            });
        }
    }
})

